const data = [{
        name: '橙子',
        cost: 2.02,
        unitPrice: 5.12
    },
    {
        name: '草莓',
        cost: 5.33,
        unitPrice: 20.98
    },
    {
        name: '香蕉',
        cost: 3.92,
        unitPrice: 10.26
    },
    {
        name: '梨子',
        cost: 4.67,
        unitPrice: 8.54
    },
    {
        name: '苹果',
        cost: 2.69,
        unitPrice: 4.35
    },
    {
        name: '火龙果',
        cost: 8.33,
        unitPrice: 30.15
    },
    {
        name: '哈密瓜',
        cost: 6.31,
        unitPrice: 24.93
    },
    {
        name: '西瓜',
        cost: 1.69,
        unitPrice: 3.48
    },
    {
        name: '柠檬',
        cost: 3.61,
        unitPrice: 16.24
    },
    {
        name: '荔枝',
        cost: 8.25,
        unitPrice: 23.41
    },
]

let dealData = []
let timer = null
let table = document.getElementsByTagName('table')[0]
let tbody = document.getElementsByTagName('tbody')[0]
let tfoot = document.getElementsByTagName('tfoot')[0]
let maxSaleNum = document.getElementsByClassName('maxSaleNum')[0]
let maxSaleVolume = document.getElementsByClassName('maxSaleVolume')[0]
let maxSaleProfit = document.getElementsByClassName('maxSaleProfit')[0]
let statisticsDomNum = document.getElementsByClassName('statisticsNum')[0]
let statisticsDomPrice = document.getElementsByClassName('statisticsPrice')[0]
let statisticsDomProfit = document.getElementsByClassName('statisticsProfit')[0]
let statisticsDomRate = document.getElementsByClassName('statisticsRate')[0]

// 目标元素保留两位小数
const fixTwo = target => {
    return Number(target).toFixed(2)
}

// 生成一个(lowNum ~ upNum)的随机数
const randomNum = (lowNum, upNum) => {
    let num = upNum - lowNum + 1
    return Math.random() * num + lowNum
}

// 深克隆
const deepClone = (target) => {
    let result
    if (typeof target !== 'object' || target === null) return target
    if (Array.isArray(target)) {
        result = []
        target.forEach((item, i) => {
            result.push(deepClone(target[i]))
        })
    } else {
        result = {}
        for (let i in target) {
            result[i] = deepClone(target[i])
        }
    }
    return result
}

// 生成实时数据并处理
const getData = () => {
    let saleObj = data[Math.floor(randomNum(0, 9))]
    let dealObj = deepClone(saleObj)
    const {
        name,
        cost,
        unitPrice
    } = dealObj

    let newObj = {
        name,
        cost,
        unitPrice,
        totalNum: Number(fixTwo(randomNum(10, 50)))
    }
    newObj.totalPrice = Number(fixTwo(newObj.totalNum * unitPrice))
    newObj.profit = Number(fixTwo((unitPrice - cost) * newObj.totalNum))
    newObj.profitRate = Number(fixTwo((unitPrice - cost) * newObj.totalNum / unitPrice))
    return newObj
}

// 创建td单元格
const createTD = (list) => {
    // 创建单元格时把统计依次添加进去
    statisticsDomNum.innerHTML = Number(fixTwo(statistics(list, 'totalNum')))
    statisticsDomPrice.innerHTML = Number(fixTwo(statistics(list, 'totalPrice')))
    statisticsDomProfit.innerHTML = Number(fixTwo(statistics(list, 'profit')))
    statisticsDomRate.innerHTML = Number(fixTwo(statistics(list, 'profitRate')))

    // let trs = tbody.getElementsByTagName('tr')
    // console.log(trs);
    // for (let i = 0; i < trs.length; i++) {
    //     debugger
    //     console.log(trs[i]);
    //     tbody.removeChild(trs[i])
    //     i--
    // }
    // while (trs.length) {
    //     tbody.removeChild(trs[0])
    // }
    // console.log(trs.length);
    // 每次创建td时，先把外面容器移除
    tbody.remove()
    tbody = document.createElement('TBODY')
    // console.log(list);
    list.forEach((item, i) => {
        maxSaleNum.innerHTML = maxSaleByNum(list, 'totalNum')['totalNum'] + '/' + maxSaleByNum(list, 'totalNum')['name']
        maxSaleVolume.innerHTML = maxSaleByNum(list, 'totalPrice')['totalPrice'] + '/' + maxSaleByNum(list, 'totalPrice')['name']
        maxSaleProfit.innerHTML = maxSaleByNum(list, 'profit')['profit'] + '/' + maxSaleByNum(list, 'profit')['name']

        // console.log(maxSaleByNum(list, 'totalNum'));

        // 创建 tr 和 td
        let tr = document.createElement('TR')
        Object.keys(item).forEach((key, k) => {
            if (key === 'cost') return
            if (key === 'unitPrice') return
            let td = document.createElement('TD')
            td.innerHTML = item[key]
            tr.appendChild(td)
        })

        tbody.appendChild(tr)
        // table.appendChild(tbody)
    })
    table.appendChild(tbody)
}

let saleList = []
// 遍历数组，删除相同名字的元素
const compareArr = (obj) => {

    // for (let i = 0; i < list.length; i++) {
    //     for (let j = i + 1; j < list.length; j++) {
    //         if (list[i].name === list[j].name) {
    //             list[i].totalNum = Number(fixTwo(list[i].totalNum + list[j].totalNum))
    //             list[i].totalPrice = Number(fixTwo(list[i].totalPrice + list[j].totalPrice))
    //             list[i].profit = Number(fixTwo(list[i].profit + list[j].profit))
    //             list[i].profitRate = Number(fixTwo((list[i].unitPrice - list[i].cost) * (list[i].totalNum + list[j].totalNum) / list[i].unitPrice))
    //             list.splice(j, 1)
    //             j--
    //         }
    //     }
    // }

    // let arr = []
    // list.map((e, i) => {
    //     if (!arr.length) {
    //         arr.push(e)
    //         e.used = true
    //     }
    //     if (arr.length) {
    //         let _index = arr.findIndex(el => el.name === e.name && !e.used)
    //         // console.log(_index);
    //         if (_index !== -1) {
    //             // console.log(arr[_index].totalNum, e.totalNum);
                // arr[_index].totalNum = Number(fixTwo(arr[_index].totalNum + e.totalNum))
                // arr[_index].totalPrice = Number(fixTwo(arr[_index].totalPrice + e.totalPrice))
                // arr[_index].profit = Number(fixTwo(arr[_index].profit + e.profit))
                // arr[_index].profitRate = Number(fixTwo((arr[_index].unitPrice - arr[_index].cost) * (arr[_index].totalNum + e.totalNum) / arr[_index].unitPrice))
    //         } else {
    //             e.used ? '' :arr.push(e)
    //         }
    //     }
    // })
    // arr.forEach((item, i) => {
    //     // 如果存在used，则删除该属性
    //     item.used ? delete item.used: ''
    // })
    // // console.log(arr);
    // // 创建td
    // createTD(arr)
    // console.log(list);

    // console.log(obj);
    
    if(saleList.length === 0) {
        // obj.used = true
        saleList.push(obj)
        createTD(saleList)
        return
    }
    if(saleList.length) {
        let _index = saleList.findIndex(el => el.name === obj.name)
        // console.log(_index);
        if(_index !== -1) {
            saleList[_index].totalNum = Number(fixTwo(saleList[_index].totalNum + obj.totalNum))
            saleList[_index].totalPrice = Number(fixTwo(saleList[_index].totalPrice + obj.totalPrice))
            saleList[_index].profit = Number(fixTwo(saleList[_index].profit + obj.profit))
            saleList[_index].profitRate = Number(fixTwo((saleList[_index].unitPrice - saleList[_index].cost) * (saleList[_index].totalNum + obj.totalNum) / saleList[_index].unitPrice))
        }else {
            saleList.push(obj)
        }
    }
    
    console.log(saleList);
    createTD(saleList)

}

// 判断数组中最高数量
const maxSale = (list, key) => {
    let newArr = []
    let maxArr = list.map((item, i) => {
        newArr.push(item[key])
        return newArr.sort((a, b) => b - a)
    })
    return maxArr[0][0]
}

// 拿到数组的最大一个值的对象
const maxSaleByNum = (list, key) => {
    const newList = deepClone(list)
    newList.sort((a, b) => b[key] - a[key])
    return newList[0]
}

// 合计数量
const statistics = (list, key) => {
    let newArr = []
    let dealArr = list.map((item, i) => {
        newArr.push(item[key])
        return newArr
    })
    return dealArr[0].reduce((pre, cur) => {
        return pre + cur
    }, 0)
}

// 每隔2秒把生成的数据添加到一个数组中
const getDataArr = () => {
    let newArr = []
    timer = setInterval(() => {
        let dataObj = getData()
        // newArr.push(dataObj)
        // 对象数组比较方法
        // compareArr(newArr)
        compareArr(dataObj)
    }, 2000)
}

// 页面加载时调用方法
getDataArr()

// 20秒后清理定时器
setTimeout(() => {
    clearInterval(timer)
}, 40000)